package com.stone.message.adapter.listener;

import com.stone.message.adapter.domain.event.SendMessageEvent;
import com.stone.message.adapter.infra.sender.MessageSender;
import org.springframework.context.ApplicationListener;
import org.springframework.lang.NonNull;

import java.util.List;

/**
 * 消息发布监听器，如果容器中发布了SendMessageEvent类型的事件，则自动回调onApplicationEvent
 *
 * @author Mr_wenpan@163.com 2021/6/28 2:09 下午
 */
public class SendMessageEventListener implements ApplicationListener<SendMessageEvent> {

    /**
     * 消息发送器，如何处理这个消息交给用户实现
     */
    private final List<MessageSender> messageSenders;

    public SendMessageEventListener(List<MessageSender> messageSenders) {
        this.messageSenders = messageSenders;
    }

    @Override
    public void onApplicationEvent(@NonNull SendMessageEvent sendMessageEvent) {
        // 消息处理，交给用户实现，这里可用线程池做异步处理（需要保证可靠性）
        messageSenders.forEach(messageSender -> messageSender.send(sendMessageEvent));
    }
}